#include "../include/SmartHomeMonitorServer.hpp"
#include "../include/Mylogger.hpp"
namespace wd{



SmartHomeMonitorServer::SmartHomeMonitorServer(unsigned short port, const string ip, int threadNum, int sizeQue)
    :_threadpool(threadNum,sizeQue)
     ,_server(port,ip)
{

    using namespace std::placeholders;
    _server.setAllCallbacks(
                            std::bind(&SmartHomeMonitorServer::onConnection,this,_1),
                            std::bind(&SmartHomeMonitorServer::onMessage,this,_1),
                            std::bind(&SmartHomeMonitorServer::onClosed,this,_1));
}

void SmartHomeMonitorServer::start(){

#if 0
    static std::once_flag flag;
    std::call_once(flag, [this]() {
                   LOG_INFO("启动线程池和服务器...");
                   _threadpool.start();
                   _server.start();

                   std::thread recorderThread([this]() {
                                              LOG_INFO("异步启动摄像头录制...");
                                              startAllRecorders();
                                              });
                   recorderThread.detach();
                   });

#endif



#if 1
    // 创建一个线程来异步启动摄像头录制
    std::thread recorderThread([this]() {
                               LOG_INFO("异步启动摄像头录制...");
                               startAllRecorders();
                               });
    recorderThread.detach(); // 分离线程，让其独立运行

    /* LOG_INFO("启动摄像头录制..."); */
    /* startAllRecorders(); */

    LOG_INFO("启动线程池和服务器...");
    _threadpool.start();
    _server.start();


    /* _threadpool.start(); */
    /* _server.start(); */
    /* startAllRecorders(); // 启动所有摄像头录制 */
#endif

}

//======================================//
// 启动所有摄像头的录制（硬编码方式）
void SmartHomeMonitorServer::startAllRecorders() {
    cout << "0000000000000" << endl;
    // 硬编码摄像头信息：摄像头ID -> RTSP地址
    std::vector<std::pair<std::string, std::string>> cameras = {
    //    {"rtsp://admin:admin@192.168.5.100/live/chn=0","1"},
        {"rtsp://admin:admin@192.168.5.222/live/chn=0","2"},

        // 可根据需要添加更多摄像头
    };

    if (cameras.empty()) {
        LOG_INFO("未配置任何摄像头，无需启动录制");
        return;
    }

    // 为每个摄像头创建录制器并启动
    for (const auto& camera : cameras) {
        const std::string& cameraId = camera.first;
        const std::string& rtspUrl = camera.second;

        auto recorder = std::make_unique<RTSPRecorder>(cameraId, rtspUrl);

        if (recorder->startRecord()) {
            _recorders[cameraId] = std::move(recorder);
            LOG_INFO("摄像头 " + cameraId + " 开始录制（RTSP: " + rtspUrl + "）");
        } else {
            LOG_ERROR("摄像头 " + cameraId + " 启动录制失败");
        }
    }
}



void SmartHomeMonitorServer::stop(){
    _threadpool.stop();
    _server.stop();
}

void SmartHomeMonitorServer::onConnection(wd::TcpConnectionPtr conn){
    //cout << "has connected su" << endl;
    LOG_INFO(conn->toString() + "has connected successfully");
}

void SmartHomeMonitorServer::onMessage(wd::TcpConnectionPtr conn){



    //1.解析网络字节流为TLV,分析消息类型

    //2.解析TLV为Packet

    Packet packet;
    //3.交给计算线程
    //解析TLV格式后的消息放到packet中
    int ret = conn->readPacket(packet);

    cout << "on Message" << endl;
    cout <<"type: " << packet.type << endl;
    cout <<"len: " << packet.length << endl;
    string mmsg = packet.msg;
    cout <<"data: " << mmsg << endl;



    if(ret < 0){
        LOG_ERROR("readPacket error");
    }


    switch(packet.type){
    case TASK_TYPE_LOGIN_SECTION1:
        {
            LOG_INFO("登录阶段一");
            UserLoginSection1 userLogin1(conn,packet);
            _threadpool.addTask(std::bind(&UserLoginSection1::process,userLogin1));

        }
        break;

    case TASK_TYPE_LOGIN_SECTION2:
        {
            LOG_INFO("登录阶段二");
            UserLoginSection2 userLogin2(conn,packet);
            _threadpool.addTask(std::bind(&UserLoginSection2::process,userLogin2));
        }
        break;
    case TASK_TYPE_REGISTER1:
        {
            LOG_INFO("注册阶段一");
            UserRegisterSection1 userRegister1(conn,packet);
            _threadpool.addTask(std::bind(&UserRegisterSection1::process,userRegister1));

        }
        break;
    case TASK_TYPE_REGISTER2:
        {
            LOG_INFO("注册阶段二");
            UserRegisterSection2 userRegister2(conn,packet);
            _threadpool.addTask(std::bind(&UserRegisterSection2::process,userRegister2));
        }
        break;
    case TASK_TYPE_GET_CAMERALIST:
        {
            LOG_INFO("获取摄像头列表");
            UserGetCameraList userGetList(conn,packet);
            _threadpool.addTask(std::bind(&UserGetCameraList::process,userGetList));
            break;
        }

    case TASK_TYPE_GET_PACKET:
        {
            LOG_INFO("发送RTSP到客户端");
            UserGetRTSP sendRtsp(conn,packet);
            _threadpool.addTask(std::bind(&UserGetRTSP::process,sendRtsp));
            cout <<"addTask" << endl;
            break;
        }

    case TASK_TYPE_GET_VIDEO:
        {
            LOG_INFO("发送录像给客户端");
            UserGetRecordings sendRecords(conn,packet);
            _threadpool.addTask(std::bind(&UserGetRecordings::process,sendRecords));
        }


    }
}


void SmartHomeMonitorServer::onClosed(wd::TcpConnectionPtr conn){
    LOG_INFO(conn->toString() + "hsa closed");
}


// 启动所有摄像头的录制（硬编码方式）





}//end of namespace wd
